package com.ap.vogellatutorial;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class StaxWriter {

	private String configFile;
	
	public void setFile(String configFile){
		this.configFile=configFile;
	}
	
	public void saveConfig(){
		XMLOutputFactory outputFactory=XMLOutputFactory.newInstance();
		
		try{
			XMLEventWriter eventWriter=outputFactory.
				createXMLEventWriter(new FileOutputStream(this.configFile));
			
			  XMLEventFactory eventFactory = XMLEventFactory.newInstance();
			  XMLEvent end = eventFactory.createDTD("\n");
			  
			   StartDocument startDocument = eventFactory.createStartDocument();
			    eventWriter.add(startDocument);
			    
			    // Create config open tag
			    StartElement configStartElement = eventFactory.createStartElement("",
			        "", "config");  
			    
			    eventWriter.add(configStartElement);
			    eventWriter.add(end);
			    
			    // Write the different nodes
			    createNode(eventWriter, "mode", "1");
			    createNode(eventWriter, "unit", "901");
			    createNode(eventWriter, "current", "0");
			    createNode(eventWriter, "interactive", "0");

			    eventWriter.add(eventFactory.createEndElement("", "", "config"));
			    eventWriter.add(end);
			    eventWriter.add(eventFactory.createEndDocument());
			    eventWriter.close(); 
			    
		}
		catch(XMLStreamException e){
			e.printStackTrace();
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
	
	
	  private void createNode(XMLEventWriter eventWriter, String name,
		      String value) throws XMLStreamException {

		    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
		    XMLEvent end = eventFactory.createDTD("\n");
		    XMLEvent tab = eventFactory.createDTD("\t");
		    // Create Start node
		    StartElement sElement = eventFactory.createStartElement("", "", name);
		    eventWriter.add(tab);
		    eventWriter.add(sElement);
		    // Create Content
		    Characters characters = eventFactory.createCharacters(value);
		    eventWriter.add(characters);
		    // Create End node
		    EndElement eElement = eventFactory.createEndElement("", "", name);
		    eventWriter.add(eElement);
		    eventWriter.add(end);

		  }
	
}
